package com.hr.action;

import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

import cn.afterturn.easypoi.entity.ImageEntity;
import cn.afterturn.easypoi.word.WordExportUtil;
import com.base.Const;
import com.base.CoreConstants;
import com.base.dao.model.BFile;
import com.base.dao.model.BFileExample;
import com.base.date.DateUtil;
import com.base.dialect.PaginationSupport;
import com.base.dao.model.Ret;
import com.base.dao.model.Grid;
import com.base.io.FileUtil;
import com.base.security.util.UserUtils;
import com.base.service.BFileService;
import com.base.util.StringUtil;
import com.hr.HrConstants;
import com.hr.dao.model.*;
import com.hr.daoEx.model.ContractEx;
import com.hr.service.ContractPathService;
import com.hr.service.OrgService;
import com.item.ConstantsCode;
import com.item.dao.model.Admin;
import com.item.service.AdminService;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.omg.CORBA.OBJECT_NOT_EXIST;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.apache.commons.lang.StringUtils;
import com.base.util.JSONUtils;
import com.base.web.annotation.LoginFilter;
import org.springframework.beans.factory.annotation.Autowired;
import com.base.action.CoreController;
import com.hr.service.ContractService;

/**
@author sun
*/
@RequestMapping("contract")
@Controller
@LoginFilter
public class ContractController extends CoreController{

    @Autowired
    private ContractService contractService;
	@Autowired
	private AdminService adminService;
	@Autowired
	private OrgService orgService;
	@Autowired
	private ContractPathService contractPathService;
	@Autowired
	private BFileService bFileService;


    @RequestMapping("/list")
	@ResponseBody
    public String list(Integer page, Integer rows, Integer cityId,Integer pointId ,String idCard, String name, String phone,String type){
    	//String id = getSessionParameter("id");
    	//System.out.println(id);
		Integer id = UserUtils.getPrincipal().getId();
		System.out.println(id);

		Admin admin = adminService.selectByPrimaryKey(id);

    	PaginationSupport.byPage(page, rows);
		Map<String, Object> map = new HashMap<String, Object>();
		if("kehu".equals(admin.getRoleCode())){
			map.put("orgCode",admin.getOrgId());
		}

		map.put("cityId",cityId);
		map.put("pointId",pointId);

		map.put("idCard",idCard);
		map.put("name",name);
		map.put("phone",phone);
		map.put("type",type);
		List<ContractEx> list = contractService.selectList(map);
		List<ContractEx> newList = new ArrayList<>();

		for(ContractEx ex : list){
			ContractEx c = new ContractEx();
			if(null != ex.getConName()){
				if(!"kehu".equals(admin.getRoleCode())){
					//是admin
					c.setRole(1);
				}else{
					c.setRole(0);
				}
				c.setId(ex.getId());
				c.setConId(ex.getConId());
				c.setOrgCode(ex.getOrgCode());
				c.setCityId(ex.getCityId() == null? null : ex.getCityId());
				c.setPointId(ex.getPointId() == null? null : ex.getPointId());
				c.setState(ex.getState() == null? null : ex.getState());
				c.setName(ex.getName() == null? null : ex.getName());
				c.setSex(ex.getSex() == null? null : ex.getSex());
				c.setPhone(ex.getPhone() == null? null : ex.getPhone());
				c.setIdCard(ex.getIdCard() == null? null : ex.getIdCard());
				c.setAddress(ex.getAddress() == null? null : ex.getAddress());
				c.setIdAddress(ex.getIdAddress() == null? null : ex.getIdAddress());
				c.setCirName(ex.getCirName() == null? null : ex.getCirName());
				c.setCirPhone(ex.getCirPhone() == null? null : ex.getCirPhone());
				c.setJob(ex.getJob() == null? null : ex.getJob());
				c.setMoney(ex.getMoney() == null? null : ex.getMoney());
				c.setJoinTime(ex.getJoinTime() == null? null : ex.getJoinTime());
				c.setEndTime(ex.getEndTime() == null? null : ex.getEndTime());
				c.setType(ex.getType() == null? null : ex.getType());
				c.setReadPath(ex.getReadPath() == null? null : ex.getReadPath());
				c.setYzPath(ex.getYzPath() == null? null : ex.getYzPath());
				c.setSignPath(ex.getSignPath() == null? null : ex.getSignPath());
				c.setCreateTime(ex.getCreateTime() == null? null : ex.getCreateTime());
				c.setOrgName(ex.getOrgName() == null? null : ex.getOrgName());
				c.setCityName(ex.getCityName() == null? null : ex.getCityName());
				c.setPointName(ex.getPointName() == null? null : ex.getPointName());
				c.setConName(ex.getConName() == null? null : ex.getConName());
				c.setFilePathId(ex.getFilePathId() == null? null : ex.getFilePathId());
				c.setConTitle(ex.getConTitle() == null? null : ex.getConTitle());
				c.setEduction(ex.getEduction() == null? null : ex.getEduction());
				newList.add(c);

			}
		}
      	return page(newList);
    }

    @RequestMapping("/save")
	@ResponseBody
    public String save(Contract contract){

		Integer id = UserUtils.getPrincipal().getId();

		Admin admin = adminService.selectByPrimaryKey(id);
    	contract.setOrgCode(admin.getOrgId().toString());

    	//找出这个公司下的印章
		ContractPathExample example = new ContractPathExample();
		example.createCriteria().andUserRoleEqualTo(id.toString());
		List<ContractPath> list = contractPathService.selectByExample(example);
		contract.setYzPath(list.get(0).getFilePath());

    	if (contract.getId() == null){
				Date endDate = DateUtil.addMonth(contract.getJoinTime(), HrConstants.contractYear * 12);
				contract.setEndTime(endDate);

    		contractService.insert(contract);

    	}else{
    		contractService.updateByPrimaryKeySelective(contract);

    	}

    	//生成合同
		createCon(contract.getId(),admin.getId());
       	return ok();
    }

	@RequestMapping("/userResign")
	@ResponseBody
	public String userResign(Contract contract){
		Contract c = contractService.selectByPrimaryKey(contract.getId());
		c.setType(contract.getType());
		contractService.updateByPrimaryKeySelective(c);
		return ok();
	}

    @RequestMapping("/findById")
	@ResponseBody
    public String find(Integer id){
    	Contract contract = contractService.selectByPrimaryKey(id);
       	return ok(contract);
    }

    @RequestMapping("/del")
	@ResponseBody
    public String del(String id){
    	String[] ids = id.split(",");
    	for (String str : ids){
    		contractService.deleteByPrimaryKey(Integer.parseInt(str));
    	}
       	return ok();
    }

	@RequestMapping("/ContractList")
	@ResponseBody
	public List<Contract> ContractList(){
		ContractExample example = new ContractExample();
		example.setOrderByClause("create_time desc");
		List<Contract> list = contractService.selectByExample(example);
		return list;
	}

	/**
	 * 获取组织名称
	 * @return
	 */
	@RequestMapping("/selectOrg")
	@ResponseBody
	public Org selectOrg(){

		ContractExample example = new ContractExample();
		Integer id = UserUtils.getPrincipal().getId();

		Admin admin = adminService.selectByPrimaryKey(id);
		Org org = orgService.selectByPrimaryKey(admin.getOrgId());
		return org;
	}

	//下载合同
	@RequestMapping("/downFile")
	@ResponseBody
	public Ret downFile(Integer id){
		Integer id2 = UserUtils.getPrincipal().getId();

		Admin admin = adminService.selectByPrimaryKey(id2);
		Contract record = contractService.selectByPrimaryKey(id);
//		if(0 != record.getType() && 2 != record.getType()){
//			//如果已经签名，重新生成合同
//			createCon(record.getId(),admin.getId());
//		}
		//找出file
		BFile bFile = bFileService.selectByPrimaryKey(record.getReadPath());
		if(null == bFile){
			return new Ret(-1,"不存在");
		}
		return new Ret(1,bFile.getFileId());
	}

	//
	@RequestMapping("/userRole")
	@ResponseBody
	public Ret userRole(){
		Integer id = UserUtils.getPrincipal().getId();

		Admin admin = adminService.selectByPrimaryKey(id);
		if("kehu".equals(admin.getRoleCode())){
			return new Ret(0);
		}
		return new Ret(1);
	}

	//详情
	@RequestMapping("/detail")
	@ResponseBody
	public ContractEx detail(Integer id){
		ContractEx record = contractService.checkDetail(id);
		return record;
	}

	//逻辑删除
	@RequestMapping("/delRecord")
	@ResponseBody
	public String delRecord(Contract contract){
		Contract record = contractService.selectByPrimaryKey(contract.getId());
		record.setIsDel(contract.getIsDel());
		contractService.updateByPrimaryKeySelective(record);
		return ok();
	}


	/**
	 * 生成合同
	 * @param id 合同id
	 * @param orgId 组织id
	 * @return
	 */
	public  Ret createCon(Integer id, Integer orgId){
		Contract contract = contractService.selectByPrimaryKey(id);
		//找到模板
		ContractPath contractPath = contractPathService.selectByPrimaryKey(Integer.parseInt(contract.getConId()));
		//找出file表环境
		BFile data = bFileService.selectByPrimaryKey(contractPath.getFilePath());
		if(null == contractPath){
			return new Ret(-1,"内容不存在");
		}

		//查询是否已经生成合同
		//if(StringUtil.isBlank(contract.getReadPath())){
		//没有生成
		System.out.println("***********开始生成合同文件");
		BFile bFile = new BFile();
		bFile.setFileId(UUID.randomUUID().toString().replaceAll("-",""));
		bFile.setFileBelong(data.getFileBelong());
		bFile.setFilePath("zip"+"/"+ bFile.getFileId()+".docx");
		bFile.setFileMinitype(data.getFileMinitype());
		bFile.setFileName(contract.getName() + "-" + data.getFileName());
		bFile.setFileState(data.getFileState());
		bFileService.insert(bFile);
		//}

		ContractEx record = contractService.selectDetail(contract.getId());


		Map<String, Object> params = new HashMap<>();
//			ImageEntity image = new ImageEntity(img,50,50);
//			params.put("img",image);//印章
		BFile imgFile = bFileService.selectByPrimaryKey(contract.getYzPath());
		String path2 = ConstantsCode.FILE_PATH + imgFile.getFilePath();
		byte[] img = FileUtil.readBytes(path2);
		ImageEntity image = new ImageEntity(img,50,50);
		params.put("img",image);//印章

		//判断用户是否已经签名
		if(0 != contract.getType() && 2 != contract.getType()){
			BFile imgFile2 = bFileService.selectByPrimaryKey(contract.getSignPath());
			String userSign = ConstantsCode.FILE_PATH + imgFile.getFilePath();
			byte[] userSignImg = FileUtil.readBytes(userSign);
			ImageEntity userSign2 = new ImageEntity(img,50,50);
			params.put("userSign",userSign2);//用户签名
		}else{
			params.put("userSign","待签名");
		}
		params.put("name",record.getName());//乙方名称
		params.put("idCard",record.getIdCard());//乙方身份证
		params.put("today", DateUtil.dateToStr(new Date()).substring(0,10));

			params.put("orgName",record.getOrgName());//机构名称


			params.put("address",record.getAddress() == null? "" : record.getAddress());//乙方住址
			params.put("idAddress",record.getIdAddress() == null? "" : record.getIdAddress());//乙方户籍地址
			params.put("phone",record.getPhone());//乙方联系电话
			params.put("cirName",record.getCirName() == null? "" : record.getCirName());//紧急联系人姓名
			params.put("cirPhone",record.getCirPhone() == null? "" : record.getCirPhone());//紧急联系人电话


			//正式合同开始时的起始
			params.put("joinYear",DateUtil.getYear(record.getJoinTime()));//合同开始年份
			params.put("joinMonth",DateUtil.getMonth(record.getJoinTime()));//合同开始月份
			params.put("joinDay",DateUtil.getDay(record.getJoinTime()));//合同开始日期
			//正式合同开始时的结束
			params.put("endYear",DateUtil.getYear(record.getEndTime()));//合同结束的年份
			params.put("endMonth",DateUtil.getMonth(record.getEndTime()));//合同结束的月份
			params.put("endDay",DateUtil.getDay(record.getEndTime()));//合同结束的日期
			//试用期结束时间
			//先找出合同开始时的日期时间加2个月
			Date testJoinEndDate = DateUtil.addMonth(record.getJoinTime(), HrConstants.contractTestMonth);

			params.put("testJoinEndYear",DateUtil.getYear(testJoinEndDate));//试用期结束年份
			params.put("testJoinEndMonth",DateUtil.getMonth(testJoinEndDate));//试用期结束月份
			params.put("testJoinEndDay",DateUtil.getDay(testJoinEndDate));//试用期结束日期
			params.put("job",record.getJob());//乙方工作
			params.put("area",record.getCityName()+record.getPointName());//工作地点--城市名称+站点名称


		try{
			XWPFDocument out = WordExportUtil.exportWord07(ConstantsCode.FILE_PATH+data.getFilePath(),params);
			FileOutputStream outputStream = new FileOutputStream(ConstantsCode.FILE_PATH+bFile.getFilePath());

			out.write(outputStream);
			outputStream.close();
			System.out.println("*************合同生成结束");
		}catch (Exception e) {
			e.printStackTrace();
		}

		contract.setReadPath(bFile.getFileId());
		contractService.updateByPrimaryKeySelective(contract);
		return new Ret(1);
	}

}